package com.seven.restaurant.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.seven.restaurant.annotation.ExistId;
import com.seven.restaurant.entity.request.CreateGroup;
import com.seven.restaurant.entity.request.FoodRequest;
import com.seven.restaurant.entity.request.PageRequset;
import com.seven.restaurant.entity.request.UpdateGroup;
import com.seven.restaurant.entity.vo.FoodDetailsVO;
import com.seven.restaurant.exception.GlobalException;
import com.seven.restaurant.exception.InfoCode;
import com.seven.restaurant.mapper.FoodMapper;
import com.seven.restaurant.service.FoodService;
import com.seven.restaurant.util.FTPUtil;
import com.seven.restaurant.util.ResponseEntity;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author BaiBan
 * @since 2022-07-18
 */
@Validated
@RestController
@RequestMapping("/food")
public class FoodController {

    @Autowired
    FoodService service;

    @Autowired
    FTPUtil ftp;

    /**
     * 菜单列表
     *
     * @param page {@link PageRequset}
     */
    @GetMapping("/list")
    public ResponseEntity<IPage<FoodDetailsVO>> list(@Validated PageRequset page) {
        return ResponseEntity.success(service.list(page));
    }

    /**
     * 添加菜品
     *
     * @param FoodRequest {@link FoodRequest}
     * @return 添加结果
     */
    @PostMapping("/create")
    public ResponseEntity<?> create(@RequestBody @Validated(CreateGroup.class) FoodRequest FoodRequest) {
        return ResponseEntity.create(service.save(FoodRequest));
    }

    /**
     * 删除菜品
     *
     * @param id 菜品id
     * @return 删除结果
     */
    @PostMapping("/delete")
    public ResponseEntity<?> delete(@ExistId(value = FoodMapper.class, message = "菜品不存在") Long id) {
        return ResponseEntity.delete(service.removeById(id));
    }

    /**
     * 修改菜品
     *
     * @param FoodRequest {@link FoodRequest}
     * @return 修改结果
     */
    @PostMapping("/update")
    public ResponseEntity<?> update(@RequestBody @Validated(UpdateGroup.class) FoodRequest FoodRequest) {
        return ResponseEntity.update(service.update(FoodRequest));
    }

    /**
     * 修改菜品的推荐属性
     *
     * @param id 菜品id
     * @return 修改结果
     */
    @PostMapping("/update/recommend")
    public ResponseEntity<?> update(@RequestBody Long id) {
        return ResponseEntity.update(service.update(id));
    }


    @PostMapping("/FoodPicture")
    public ResponseEntity<?> upload(@RequestBody MultipartFile file) throws GlobalException {

        if (file == null || file.isEmpty()) throw new GlobalException(InfoCode.FILE_NULL_ERROR);

        String icon = ftp.uploadFile(file, "Food");
        return ResponseEntity.success(new MutablePair<>("icon", icon));
    }
}